package com.shunwang.errors.engine.builder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.shunwang.errors.engine.builder.bean.NodeBean;
import com.shunwang.errors.engine.builder.bean.NodeBeans;
import com.shunwang.errors.engine.builder.bean.NodeMethod;
import com.shunwang.errors.engine.core.ErrorsHandler;
import com.shunwang.errors.engine.core.Mapper;
import com.shunwang.errors.engine.core.Mapping;
import com.shunwang.errors.engine.exception.BussException;
import com.shunwang.errors.engine.handler.Handler;
import com.shunwang.errors.engine.util.ClazzUtil;
import com.shunwang.errors.exception.ParserException;

public abstract class LoggerParser {

	protected NodeBeans nodeBeans = new NodeBeans();
	
    public ErrorsHandler parser() throws Exception{
        parserData();
        return buildLoggerHandler();
    }
    
    protected abstract void parserData()throws IOException,ParserException;
    
	protected ErrorsHandler buildLoggerHandler() throws Exception {
		Mapper mapper = new Mapper();
		buildMapper(mapper,nodeBeans);
		ErrorsHandler handler = new ErrorsHandler();
		handler.setMapper(mapper);
		return handler;
	}
	
    protected void buildMapper(Mapper mapper, NodeBeans nodes) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		List<NodeBean> list = nodes.getList();
		for(int j=0;j<list.size();j++){
			NodeBean node = list.get(j);
			List<NodeMethod> method = node.getMethod();
			for(int i=0;i<method.size();i++){
				Mapping mapping = createMapping(method.get(i));
				mapper.setMapping(node.getClazz()+"."+method.get(i).getMethodName(), mapping);
			}
		}
	}
    protected Mapping createMapping(NodeMethod node) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Mapping mapping = new Mapping();
		Handler handler = (Handler)ClazzUtil.newInstance(node.getHandClazz());
		
		List<StringBuffer> method = node.getExClazz();
		for(int i=0;i<method.size();i++){
			Throwable throwable = (Throwable)ClazzUtil.newInstance(method.get(i).toString());
			mapping.addMapping(throwable, handler);
		}
		return mapping;
	}

}
